<?php

declare(strict_types=1);

namespace app\common\service\sys;

use app\common\traits\ServiceTrait;
use app\common\dao\sys\LogDao;

/**
 * 系统日志
 * @author:kaige
 * @update:2022-06-12
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class LogService
{
  protected $dao = null;

  public function __construct()
  {
    $this->dao = new LogDao();
  }
  use ServiceTrait;

  public function _list_with()
  {
    return  ['glmenu'];
  }

  /**
   * 重写 列表搜索条件
   * @param $post
   * @return mixed
   */
  public function _list_where($post)
  {
    $where = [];
    if (isset($post['search_username']) && !empty($post['search_username'])) {
      $where[] = ['un', '=', $post['search_username']];
    }
    if (isset($post['search_ip']) && !empty($post['search_ip'])) {
      $where[] = ['ip', '=', $post['search_ip']];
    }
    if (isset($post['search_content']) && !empty($post['search_content'])) {
      $where[] = ['content', 'like', '%' . $post['search_content'] . '%'];
    }
    if (isset($post['search_date']) && !empty($post['search_date'])) {
      $date_string = $post['search_date'];
      $date_array = explode('～', urldecode($date_string));
      $stime = strtotime($date_array[0] . '00:00:00');
      $etime = strtotime($date_array[1] . '23:59:59');
      $where[] = ['create_time', 'between', [$stime, $etime]];
    }
    $result['where'] = $where;
    $result['field'] = [];
    $result['order'] = ['id' => 'desc'];
    return $result;
  }

  /**
   * 重写 输出格式化
   */
  public function _list_format($list)
  {
    //纯真数据库
    // if ($list && is_array($list)) {
    //   $iplocate = new \app\common\util\Iplocate();
    //   foreach ($list as $k => &$v) {
    //     if ($v['ip'] && !empty($v['ip'])) {
    //       $v['ip_addr'] = $iplocate->getaddress($v['ip']);
    //     }
    //   }
    // }
    if ($list && is_array($list)) {
      $ip2region = new \Ip2Region();
      foreach ($list as $k => &$v) {
        if ($v['ip'] && !empty($v['ip'])) {
          $v['ip_addr'] = $ip2region->btreeSearch($v['ip']);
          $v['ip_addr'] = str_replace('0','',$v['ip_addr']);
          $v['ip_addr'] = str_replace('|','',$v['ip_addr']);
        }
      }
    }
    return $list;
  }

  /**
   * ip2region 使用
   * $ip2region = new Ip2Region();
   *$ip = '101.105.35.57';
   *$info = $ip2region->btreeSearch($ip);
   *var_export($info, true);
   *  array (
   *      'city_id' => 2163,
   *     'region' => '中国|华南|广东省|深圳市|鹏博士',
   *  )
   */
}
